<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-07-20
 * Time: 9:54
 */

namespace app\helper;


use app\constant\UploadConst;
use app\libs\Utils;
use app\model\AdminOss;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Cache;
use think\facade\Request;

class OssHelper
{
    const IMG=0;
    const VIDEO=1;
    const OTHER=10;

    /**
     * 通过服务器中转上传阿里云oss
     * @param int $tid
     * @param int $uid
     * @return array|string
     */
    public static function uploadFile($tid = -1,$uid=-1)
    {
        $file = request()->file('file');  //获取到上传的文件

        $arr = null;
        // 尝试执行
        try {
            $type = CommonHelper::getFileExName($file->getInfo()['name']);
            $fileType = self::getFileType($type);
            $config = self::getOssConfig(UploadConst::OSS,$tid);
            if (isset($file)) {
                $accessKeyId = $config['accesskey'];
                $accessKeySecret = $config['secretkey'];
                $endpoint = $config['endpoint'];
                $bucket = $config['bucket'];
                //实例化对象 将配置传入
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                //这里是有sha1加密 生成文件名 之后连接上后缀
                $userPath = '';
                if($tid!=-1){
                    $userPath=$userPath . 't' . $tid .'/';
                }
                if($uid!=-1){
                    $userPath=$userPath . 'u' . $uid .'/';
                }
                $fileName = $userPath. date('Ymd', time())."/" . uniqid() . $type;

                //执行阿里云上传
                $result = $ossClient->uploadFile($bucket, $fileName, $file->getInfo()['tmp_name']);
                /**
                 * 这个只是为了展示
                 * 可以删除或者保留下做后面的操作
                 */
                $arr = [
                    'done' => true,
                    'url' => $result['info']['url'],
                    'name' => $fileName,
                    'file_type' => $fileType,
                    'file_name' => $file->getInfo()['name']
                ];
            }
        } catch (OssException $e) {
            return $arr = [
                'done' => false,
                'msg' => $e->getMessage()
            ];
        }
        return $arr;
    }
    public static function getFileType($type){
        $img = ['.jpg', '.jpeg', '.png', '.webp', '.gif'];
        $video = ['.avi', '.rmvb', '.rm', '.flv', '.mp4', '.3GP'];
        if(in_array ($type,$img)){
            return self::IMG;
        }else if(in_array ($type,$video)){
            return self::VIDEO;
        }else{
            return self::OTHER;
        }
    }

    //删除文件
    public static function deleteOssFile($key = null,$tid)
    {
        $config = self::getOssConfig(UploadConst::OSS,$tid);
        if($key ==null){
            $key = Request::param('key');
        }
        $result = null;
        if (isset($key)) {
            $accessKeyId = $config['accesskey'];
            $accessKeySecret = $config['secretkey'];
            $endpoint = $config['endpoint'];
            $bucket = $config['bucket'];
            try {
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                $ossClient->deleteObject($bucket, $key);
                $result = [
                    'done' => true,
                    'msg' => '删除成功'
                ];
                return $result;
            } catch (OssException $e) {
                printf(__FUNCTION__ . ": FAILED\n");
                printf($e->getMessage() . "\n");
                $result = [
                    'done' => false,
                    'msg' => '删除失败' . $e->getMessage()
                ];
                return $result;
            }
        } else {
            $result = [
                'done' => false,
                'msg' => '删除失败,缺少参数key'
            ];
            return $result;
        }
    }
    //批量删除文件
    public static function deleteOssFiles($key = null,$tid)
    {
        $config = self::getOssConfig(UploadConst::OSS,$tid);
        $result = null;
        if (isset($key)) {
            $accessKeyId = $config['accesskey'];
            $accessKeySecret = $config['secretkey'];
            $endpoint = $config['endpoint'];
            $bucket = $config['bucket'];
            try {
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                $ossClient->deleteObjects($bucket, $key);
                $result = [
                    'done' => true,
                    'msg' => '删除成功'
                ];
                return $result;
            } catch (OssException $e) {
                printf(__FUNCTION__ . ": FAILED\n");
                printf($e->getMessage() . "\n");
                $result = [
                    'done' => false,
                    'msg' => '删除失败' . $e->getMessage()
                ];
                return $result;
            }
        } else {
            $result = [
                'done' => false,
                'msg' => '删除失败,缺少参数key'
            ];
            return $result;
        }
    }

    public static function getOssConfig($type,$tid=null)
    {
        $data = cache('OSS_'.$tid.'_'.$type);
        if(isset($data)&&!Utils::isEmpty($data)){
            return $data;
        }else{
            $data = AdminOss::get(['type' => $type,'tid'=>$tid], '', false);
            cache('OSS_'.$tid.'_'.$type,$data);
            return $data;
        }
    }

    /**
     * 更新缓存
     * @param int $type
     * @param $tid
     */
    public static function updateCache($type=1, $tid){
        Cache::rm('OSS_'.$tid.'_'.$type);
    }

}
